package com.whisperly.echotalk.starryb.schemas;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.appsflyer.AFInAppEventType;
import com.appsflyer.AppsFlyerLib;
import com.appsflyer.attribution.AppsFlyerRequestListener;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.whisperly.echotalk.bllmodel.BaseResponse;
import com.whisperly.echotalk.bllmodel.LoginDto;
import com.whisperly.echotalk.bllmodel.LoginResponse;
import com.whisperly.echotalk.bllmodel.ResultBody;
import com.whisperly.echotalk.bllmodel.SignUp;
import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.BaseURL;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class SplashPage extends AppCompatActivity {
    TextView title, tips, loadingText;
    private ProgressBar progressBar;
    // Animations
    Animation top, bottom, middle;
    private boolean isMainActivityStarted = false;
    private static final String LOG_TAG = "SplashPage-AF";
    private SharedPreferences loginPrefs;
    private static final String PREF_NAME = "LoginPrefs";
    private static final String KEY_REMEMBER = "remember";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";
    private static final String KEY_LOGIN_TYPE = "login_type";
    private View loadingView;
    private boolean shouldAutoLogin = false;
    private String savedUsername = "";
    private String savedPassword = "";
    private String loginType = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.initiate);

        // 设置状态栏 - 适配Android 15
        setupImmersiveStatusBar();

        // 初始化 SharedPreferences
        loginPrefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

        // 初始化其他视图和组件
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);
        AppsManager.addActivity(this);
        initializeViews();

        // 检查是否从退出登录启动
        boolean isFromLogout = getIntent().getBooleanExtra("from_logout", false);
        if (isFromLogout) {
            shouldAutoLogin = false;
            loginType = "";
            savedUsername = "";
            savedPassword = "";
        }

        // 检查是否同意隐私政策
        SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
        boolean hasAgreed = prefs.getBoolean("hasAgreed", false);

        // 使用 Handler 确保在主线程执行
        new Handler(Looper.getMainLooper()).post(() -> {
            if (!hasAgreed) {
                showAgreementDialog();
            } else {
                initializeAnimations();
                startMainActivityWithDelay();
            }
        });
    }

    /**
     * 设置沉浸式状态栏 - 适配Android 15
     */
    private void setupImmersiveStatusBar() {
        try {
            Window window = getWindow();
            if (window == null) return;

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // Android 11+ 使用新的 WindowInsetsController API
                window.getDecorView().post(() -> {
                    try {
                        WindowInsetsController insetsController = window.getInsetsController();
                        if (insetsController != null) {
                            insetsController.setSystemBarsAppearance(
                                    WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
                                    WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS
                            );
                        }

                        // 处理 WindowInsets 来避免重叠
                        ViewCompat.setOnApplyWindowInsetsListener(findViewById(android.R.id.content),
                                (v, insets) -> {
                                    Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
                                    // 给根布局添加 top padding
                                    v.setPadding(0, systemBars.top, 0, 0);
                                    return insets;
                                });
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Error setting window insets controller", e);
                    }
                });

                window.setDecorFitsSystemWindows(false);
            } else {
                // Android 10 及以下版本的兼容处理
                View decorView = window.getDecorView();
                if (decorView != null) {
                    int flags = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                    }

                    decorView.setSystemUiVisibility(flags);

                    // 为旧版本手动添加状态栏高度的 padding
                    decorView.post(() -> {
                        try {
                            int statusBarHeight = getStatusBarHeight();
                            findViewById(android.R.id.content).setPadding(0, statusBarHeight, 0, 0);
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Error setting padding for old version", e);
                        }
                    });
                }
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error in setupImmersiveStatusBar", e);
        }
    }

    /**
     * 获取状态栏高度（用于旧版本Android）
     */
    private int getStatusBarHeight() {
        int result = 0;
        try {
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = getResources().getDimensionPixelSize(resourceId);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error getting status bar height", e);
        }
        return result;
    }

    private void handleGoogleSignInResult(GoogleSignInAccount account) {
        String email = account.getEmail();
        String name = account.getDisplayName();

        // 添加加载动画
        showLoading();

        // 这里你可以使用Google账号信息进行登录或注册
        LoginDto loginDto = new LoginDto();
        loginDto.setUserName(name);
        loginDto.setEmail(email);
        loginDto.setType("Google");
        loginDto.setPassword(""); // 可能需要一个特殊的处理方式来处理Google登录

        NetworkUtils.postLogin(loginDto, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                // 确保在主线程中处理 UI 操作
                runOnUiThread(() -> {
                    hideLoading();
                    try {
                        LoginResponse data = (LoginResponse) response.getData();
                        UserWithChat user = data.getUserWithChat();
                        if (data.getSuccess()) {
                            @SuppressLint("DefaultLocale") String loginId = "Blink " + user.getUid();
                            user.setLoginId(loginId);
                            GlobalData.setUsername(name);
                            GlobalData.setUser(user.getObjectId(), user);

                            NetworkUtils.getByUserId(user.getObjectId(), new BlinkCallback() {
                                @Override
                                public void onSuccess(ResultBody<?> response) {
                                    runOnUiThread(() -> {
                                        try {
                                            if (response.getCode() == 200) {
                                                BaseResponse<?> data1 = (BaseResponse<?>) response.getData();
                                                SignUp data2 = (SignUp) data1.getData();
                                                GlobalData.setSignup(data2);

                                                if (!isFinishing() && !isDestroyed()) {
                                                    // 显示Google账号登录成功和密码提示
                                                    showGoogleLoginSuccessDialog(email);
                                                }
                                            } else {
                                                if (!isFinishing() && !isDestroyed()) {
                                                    showGoogleLoginSuccessDialog(email);
                                                }
                                            }
                                        } catch (Exception e) {
                                            Log.e(LOG_TAG, "Error processing success response", e);
                                            if (!isFinishing() && !isDestroyed()) {
                                                showLoginDialog(getString(R.string.Network_error), false);
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(Throwable throwable) {
                                    runOnUiThread(() -> {
                                        if (!isFinishing() && !isDestroyed()) {
                                            showLoginDialog(getString(R.string.Network_error), false);
                                        }
                                    });
                                }
                            });
                        } else {
                            if (!isFinishing() && !isDestroyed()) {
                                showLoginDialog(getString(R.string.Login_failed), false);
                            }
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Error processing login response", e);
                        if (!isFinishing() && !isDestroyed()) {
                            showLoginDialog(getString(R.string.Network_error), false);
                        }
                    }
                });
            }

            @Override
            public void onFailure(Throwable throwable) {
                runOnUiThread(() -> {
                    hideLoading();
                    if (!isFinishing() && !isDestroyed()) {
                        Log.e(LOG_TAG, "Google sign in API call failed", throwable);
                        showLoginDialog(getString(R.string.Network_error), false);
                    }
                });
            }
        });
    }

    private void showLoginDialog(String message, boolean flag) {
        if (isFinishing() || isDestroyed()) {
            return;
        }

        runOnUiThread(() -> {
            try {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(R.string.Prompt);
                builder.setMessage(message);
                builder.setPositiveButton(R.string.OK, (dialog, which) -> {
                    dialog.dismiss();
                    if (flag && !isFinishing() && !isDestroyed()) {
                        try {
                            Intent intent = new Intent(this, AI.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            finish();
                        } catch (Exception e) {
                            Log.e(LOG_TAG, "Error starting AI activity", e);
                        }
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.setCancelable(false);
                if (!isFinishing() && !isDestroyed()) {
                    dialog.show();
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error showing dialog", e);
            }
        });
    }

    private void handleGoogleAutoLogin() {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        if (account != null) {
            handleGoogleSignInResult(account);
        }
    }

    // 添加新方法显示Google登录成功和密码提示对话框
    private void showGoogleLoginSuccessDialog(String email) {
        if (isFinishing() || isDestroyed()) {
            return;
        }

        if (GlobalData.getUser().getDef()) {
            runOnUiThread(() -> {
                try {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle(R.string.Login_successful);

                    // 创建包含登录成功和密码提示的完整消息
                    String message = getString(R.string.Login_successful) + "\n\n" +
                            getString(R.string.google_login_password_notice, email);

                    builder.setMessage(message);
                    builder.setPositiveButton(R.string.OK, (dialog, which) -> {
                        dialog.dismiss();
                        if (!isFinishing() && !isDestroyed()) {
                            try {
                                Intent intent = new Intent(this, AI.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                                finish();
                            } catch (Exception e) {
                                Log.e(LOG_TAG, "Error starting AI activity", e);
                            }
                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.setCancelable(false);

                    if (!isFinishing() && !isDestroyed()) {
                        dialog.show();
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Error showing Google login success dialog", e);
                }
            });
        } else {
            if (!isFinishing() && !isDestroyed()) {
                try {
                    Intent intent = new Intent(this, AI.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    finish();
                } catch (Exception e) {
                    Log.e(LOG_TAG, "Error starting AI activity", e);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保清理 loadingView
        if (loadingView != null && loadingView.getParent() != null) {
            ((ViewGroup) loadingView.getParent()).removeView(loadingView);
        }
        loadingView = null;
    }

    private void handleAutoLogin(String username, String password) {
        if (username.isEmpty() || password.isEmpty()) {
            proceedToMainActivity();
            return;
        }

        showLoading();
        LoginDto loginDto = new LoginDto();
        loginDto.setUserName(username);
        loginDto.setPassword(password);

        NetworkUtils.postLogin(loginDto, new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                runOnUiThread(() -> {
                    hideLoading();
                    try {
                        LoginResponse data = (LoginResponse) response.getData();
                        UserWithChat user = data.getUserWithChat();
                        if (data.getSuccess()) {
                            handleLoginSuccess(user, username);
                        } else {
                            clearLoginCredentials();
                            proceedToMainActivity();
                        }
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "Error during auto login", e);
                        clearLoginCredentials();
                        proceedToMainActivity();
                    }
                });
            }

            @Override
            public void onFailure(Throwable throwable) {
                runOnUiThread(() -> {
                    hideLoading();
                    clearLoginCredentials();
                    proceedToMainActivity();
                });
            }
        });
    }

    private void handleLoginSuccess(UserWithChat user, String name) {
        @SuppressLint("DefaultLocale") String loginId = "Blink " + user.getUid();
        user.setLoginId(loginId);
        GlobalData.setUsername(name);
        GlobalData.setUser(user.getObjectId(), user);
        NetworkUtils.getByUserId(user.getObjectId(), new BlinkCallback() {
            @Override
            public void onSuccess(ResultBody<?> response) {
                if (response.getCode() == 200) {
                    BaseResponse<?> data1 = (BaseResponse<?>) response.getData();
                    SignUp data2 = (SignUp) data1.getData();
                    GlobalData.setSignup(data2);
                    showLoginDialog(getString(R.string.Login_successful), true);
                    Map<String, Object> eventValues = new HashMap<String, Object>();
                    eventValues.put(AFInAppEventType.LOGIN, name);
                    AppsFlyerLib.getInstance().logEvent(getApplicationContext(),
                            AFInAppEventType.LOGIN, eventValues, new AppsFlyerRequestListener() {
                                @Override
                                public void onSuccess() {
                                    Log.d(LOG_TAG, "Event sent successfully");
                                }

                                @Override
                                public void onError(int i, @NonNull String s) {
                                    Log.d(LOG_TAG, "Event failed to be sent:\n" +
                                            "Error code: " + i + "\n"
                                            + "Error description: " + s);
                                }
                            });
                    return;
                }
                showLoginDialog(getString(R.string.Network_error), false);
            }

            @Override
            public void onFailure(Throwable throwable) {
                showLoginDialog(getString(R.string.Network_error), false);
            }
        });
    }

    private void clearLoginCredentials() {
        SharedPreferences.Editor editor = loginPrefs.edit();
        editor.clear();
        editor.apply();
    }

    private void showLoading() {
        runOnUiThread(() -> {
            try {
                if (loadingView == null) {
                    loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);
                }

                if (loadingView.getParent() == null) {
                    // 创建RelativeLayout参数
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT,
                            RelativeLayout.LayoutParams.MATCH_PARENT
                    );

                    // 创建一个半透明的背景
                    loadingView.setBackgroundColor(Color.parseColor("#80000000"));

                    // 确保加载视图在最上层
                    loadingView.setElevation(Float.MAX_VALUE);

                    ViewGroup rootView = findViewById(android.R.id.content);
                    if (rootView != null) {
                        rootView.addView(loadingView, params);
                        Log.d("LoginActivity", "Loading view added");
                    }
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error showing loading view", e);
            }
        });
    }

    private void hideLoading() {
        runOnUiThread(() -> {
            try {
                if (loadingView != null && loadingView.getParent() != null) {
                    ((ViewGroup) loadingView.getParent()).removeView(loadingView);
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error hiding loading view", e);
            }
        });
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    private void checkLoginCredentials() {
        if (loginPrefs.getBoolean(KEY_REMEMBER, false)) {
            shouldAutoLogin = true;
            loginType = loginPrefs.getString(KEY_LOGIN_TYPE, "");
            if (!"google".equals(loginType)) {
                savedUsername = loginPrefs.getString(KEY_USERNAME, "");
                savedPassword = loginPrefs.getString(KEY_PASSWORD, "");
            }
        } else {
            shouldAutoLogin = false;
        }
    }

    private void initializeViews() {
        title = findViewById(R.id.splash_title);
        tips = findViewById(R.id.splash_tips);
        loadingText = findViewById(R.id.loading_text);
        progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
    }

    private void initializeAnimations() {
        bottom = AnimationUtils.loadAnimation(this, R.anim.bottom);
        middle = AnimationUtils.loadAnimation(this, R.anim.middle);
        top = AnimationUtils.loadAnimation(this, R.anim.top);
    }

    private void proceedWithAutoLoginOrMain() {
        if (!isMainActivityStarted) {
            checkLoginCredentials(); // 检查登录状态
            if (shouldAutoLogin) {
                if ("google".equals(loginType)) {
                    handleGoogleAutoLogin();
                } else {
                    handleAutoLogin(savedUsername, savedPassword);
                }
            } else {
                proceedToMainActivity();  // 直接进入主页面
            }
        }
    }

    private void proceedToMainActivity() {
        if (!isMainActivityStarted) {
            isMainActivityStarted = true;  // 先设置标志，防止重复调用
            hideLoadingIndicator();
            Intent intent = new Intent(this, AI.class);
            startActivity(intent);
            finish();
        }
    }

    // 修改 startMainActivityWithDelay 方法
    private void startMainActivityWithDelay() {
        // 确保在主线程中执行
        if (Looper.myLooper() != Looper.getMainLooper()) {
            new Handler(Looper.getMainLooper()).post(this::startMainActivityWithDelay);
            return;
        }

        Animation.AnimationListener animationListener = new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                new Handler(Looper.getMainLooper()).post(() -> proceedWithAutoLoginOrMain());
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        };

        // 设置动画监听器
        middle.setAnimationListener(animationListener);

        // 开始动画
        title.startAnimation(middle);
        tips.startAnimation(top);
    }

    private void showAgreementDialog() {
        // 在主线程中执行对话框显示
        if (Looper.myLooper() != Looper.getMainLooper()) {
            runOnUiThread(this::showAgreementDialog);
            return;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View customLayout = getLayoutInflater().inflate(R.layout.welcome_dialog, null);
        builder.setView(customLayout);

        TextView tvMessage = customLayout.findViewById(R.id.tvMessage);
        final SpannableString message = new SpannableString(getString(R.string.privacy_splashPage));

        setClickableSpan(message, getString(R.string.User_Agreement2), BaseURL.TERMS_CONDITIONS, tvMessage);
        setClickableSpan(message, getString(R.string.Privacy_Policy2), BaseURL.PRIVACY_POLICY, tvMessage);

        tvMessage.setText(message);
        tvMessage.setMovementMethod(LinkMovementMethod.getInstance());
        tvMessage.setHighlightColor(Color.YELLOW);

        AlertDialog dialog = builder.setPositiveButton(R.string.Agree, null)
                .setNegativeButton(R.string.Disagree, null)
                .setCancelable(false)
                .create();

        // 显示对话框
        dialog.show();

        // 直接执行后续操作，不使用 runOnUiThread
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            // 保存同意状态
            SharedPreferences.Editor editor = getSharedPreferences("prefs", MODE_PRIVATE).edit();
            editor.putBoolean("hasAgreed", true);
            editor.apply();

            // 关闭对话框
            dialog.dismiss();

            // 初始化动画
            initializeAnimations();

            // 启动延迟流程
            new Handler(Looper.getMainLooper()).post(this::startMainActivityWithDelay);
        });

        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(v -> {
            dialog.dismiss();
            finish();
        });
    }

    private void setClickableSpan(SpannableString spannableString, String target, String url, TextView textView) {
        int start = spannableString.toString().indexOf(target);
        int end = start + target.length();
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(true);
                ds.setColor(ContextCompat.getColor(SplashPage.this, R.color.blue));
            }
        }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    private void hideLoadingIndicator() {
        loadingText.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
    }

    public static void logout(Context context) {
        // 清除登录凭证
        SharedPreferences loginPrefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = loginPrefs.edit();
        editor.clear();
        editor.apply();

        // 清除 Google 登录状态
        GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(context,
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestEmail()
                        .requestProfile()
                        .build());
        googleSignInClient.signOut();

        // 清除全局数据
        GlobalData.reset();

        // 清除其他可能的缓存数据
        SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor appEditor = appPrefs.edit();
        appEditor.remove("lastLoginType");  // 如果有其他需要清除的键值，也在这里清除
        appEditor.apply();
    }
}